<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>OverType - Dynamic Creation Example</title>
    <style>
        body {
            font-family: system-ui, -apple-system, sans-serif;
            max-width: 1000px;
            margin: 0 auto;
            padding: 40px 20px;
            background: #f5f5f5;
        }
        
        h1 {
            color: #333;
            margin-bottom: 10px;
        }
        
        .subtitle {
            color: #666;
            margin-bottom: 30px;
        }
        
        .controls {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }
        
        button {
            padding: 10px 20px;
            border: none;
            background: #4a90e2;
            color: white;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            transition: background 0.3s;
        }
        
        button:hover {
            background: #357abd;
        }
        
        button.danger {
            background: #e74c3c;
        }
        
        button.danger:hover {
            background: #c0392b;
        }
        
        button.success {
            background: #27ae60;
        }
        
        button.success:hover {
            background: #229954;
        }
        
        .editors-container {
            display: grid;
            gap: 20px;
            margin-bottom: 20px;
        }
        
        .editor-wrapper {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            overflow: hidden;
            animation: slideIn 0.3s ease-out;
        }
        
        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(-20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .editor-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 16px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        
        .editor-title {
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .editor-id {
            font-size: 12px;
            opacity: 0.8;
            font-family: monospace;
        }
        
        .editor-actions {
            display: flex;
            gap: 8px;
        }
        
        .editor-btn {
            padding: 4px 8px;
            background: rgba(255,255,255,0.2);
            border: none;
            color: white;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
        }
        
        .editor-btn:hover {
            background: rgba(255,255,255,0.3);
        }
        
        .editor-container {
            height: 200px;
        }
        
        .stats {
            padding: 20px;
            background: #e8f5e9;
            border: 1px solid #4caf50;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        
        .stat-item {
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;
        }
        
        .stat-label {
            font-weight: 500;
            color: #2e7d32;
        }
        
        .stat-value {
            font-family: monospace;
            color: #1b5e20;
        }
        
        .options-panel {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        
        .option-group {
            display: flex;
            gap: 15px;
            margin-bottom: 15px;
            align-items: center;
        }
        
        .option-group label {
            min-width: 100px;
            font-size: 14px;
            color: #555;
        }
        
        .option-group input,
        .option-group select {
            flex: 1;
            padding: 6px 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        
        .live-indicator {
            display: inline-block;
            width: 8px;
            height: 8px;
            background: #4caf50;
            border-radius: 50%;
            animation: pulse 2s infinite;
        }
        
        @keyframes pulse {
            0%, 100% { opacity: 1; transform: scale(1); }
            50% { opacity: 0.7; transform: scale(1.2); }
        }
    </style>
</head>
<body>
    <h1>OverType Dynamic Creation Example</h1>
    <p class="subtitle">Create, manage, and destroy editors dynamically</p>
    
    <div class="stats">
        <div class="stat-item">
            <span class="stat-label">Active Editors:</span>
            <span class="stat-value" id="editorCount">0</span>
        </div>
        <div class="stat-item">
            <span class="stat-label">Total Created:</span>
            <span class="stat-value" id="totalCreated">0</span>
        </div>
        <div class="stat-item">
            <span class="stat-label">Total Characters:</span>
            <span class="stat-value" id="totalChars">0</span>
        </div>
    </div>
    
    <div class="options-panel">
        <h3>New Editor Options</h3>
        <div class="option-group">
            <label>Theme:</label>
            <select id="themeSelect">
                <option value="solar">Solar (Light)</option>
                <option value="cave">Cave (Dark)</option>
            </select>
        </div>
        <div class="option-group">
            <label>Font Size:</label>
            <select id="fontSizeSelect">
                <option value="12px">Small (12px)</option>
                <option value="14px" selected>Medium (14px)</option>
                <option value="16px">Large (16px)</option>
                <option value="18px">Extra Large (18px)</option>
            </select>
        </div>
        <div class="option-group">
            <label>Placeholder:</label>
            <input type="text" id="placeholderInput" value="Start typing markdown...">
        </div>
        <div class="option-group">
            <label>Initial Content:</label>
            <select id="contentSelect">
                <option value="empty">Empty</option>
                <option value="sample">Sample Markdown</option>
                <option value="tutorial">Tutorial</option>
                <option value="lorem">Lorem Ipsum</option>
            </select>
        </div>
    </div>
    
    <div class="controls">
        <button onclick="createEditor()" class="success">➕ Create Editor</button>
        <button onclick="createMultiple()">Create 3 Editors</button>
        <button onclick="destroyAll()" class="danger">🗑️ Destroy All</button>
        <button onclick="getAllContent()">📋 Get All Content</button>
        <button onclick="syncAllContent()">🔄 Sync Content</button>
        <button onclick="randomizeThemes()">🎨 Randomize Themes</button>
    </div>
    
    <div id="editors" class="editors-container"></div>

    <script src="../dist/overtype.js"></script>
    <script>
        const OT = window.OverType?.default || window.OverType;
        let editorInstances = [];
        let totalCreated = 0;
        
        const sampleContents = {
            empty: '',
            sample: `# Dynamic Editor ${Date.now()}

This editor was **dynamically created** at runtime!

## Features
- Dynamic creation and destruction
- Configurable options
- Real-time statistics

> Try creating multiple editors!`,
            tutorial: `# Markdown Tutorial

## Headers
# H1 Header
## H2 Header  
### H3 Header

## Emphasis
**Bold text** or __bold text__
*Italic text* or _italic text_

## Lists
- Bullet item 1
- Bullet item 2
  - Nested item

1. Numbered item 1
2. Numbered item 2

## Code
Inline \`code\` and code blocks:

\`\`\`
console.log("Hello, OverType!");
\`\`\`

## Links
[Visit GitHub](https://github.com)

## Blockquotes
> This is a blockquote
> It can span multiple lines

---

That's the basics!`,
            lorem: `# Lorem Ipsum

Lorem ipsum **dolor sit amet**, consectetur *adipiscing elit*. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

## Ut Enim Ad Minim

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

### Duis Aute Irure

Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.

> Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

1. Lorem ipsum dolor sit amet
2. Consectetur adipiscing elit
3. Sed do eiusmod tempor

- Ut labore et dolore magna aliqua
- Ut enim ad minim veniam
- Quis nostrud exercitation

\`Lorem ipsum\` dolor sit amet, [consectetur](https://example.com) adipiscing elit.`
        };
        
        function createEditor() {
            const container = document.getElementById('editors');
            const editorId = `editor-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
            
            // Get options
            const theme = document.getElementById('themeSelect').value;
            const fontSize = document.getElementById('fontSizeSelect').value;
            const placeholder = document.getElementById('placeholderInput').value;
            const contentType = document.getElementById('contentSelect').value;
            
            // Create wrapper
            const wrapper = document.createElement('div');
            wrapper.className = 'editor-wrapper';
            wrapper.id = editorId;
            
            // Create header
            const header = document.createElement('div');
            header.className = 'editor-header';
            header.innerHTML = `
                <div class="editor-title">
                    <span class="live-indicator"></span>
                    Editor #${totalCreated + 1}
                    <span class="editor-id">${editorId}</span>
                </div>
                <div class="editor-actions">
                    <button class="editor-btn" onclick="toggleTheme('${editorId}')">Theme</button>
                    <button class="editor-btn" onclick="exportContent('${editorId}')">Export</button>
                    <button class="editor-btn" onclick="destroyEditor('${editorId}')">✕</button>
                </div>
            `;
            
            // Create editor container
            const editorDiv = document.createElement('div');
            editorDiv.className = 'editor-container';
            
            // Assemble
            wrapper.appendChild(header);
            wrapper.appendChild(editorDiv);
            container.appendChild(wrapper);
            
            // Initialize OverType
            const [instance] = new OT(editorDiv, {
                theme: theme,
                fontSize: fontSize,
                placeholder: placeholder,
                value: sampleContents[contentType],
                onChange: (value) => {
                    updateStats();
                }
            });
            
            // Store instance
            editorInstances.push({
                id: editorId,
                instance: instance,
                theme: theme
            });
            
            totalCreated++;
            updateStats();
            
            console.log(`Created editor: ${editorId}`);
        }
        
        function createMultiple() {
            for (let i = 0; i < 3; i++) {
                setTimeout(() => createEditor(), i * 100);
            }
        }
        
        function destroyEditor(editorId) {
            const index = editorInstances.findIndex(e => e.id === editorId);
            if (index !== -1) {
                // Destroy OverType instance
                editorInstances[index].instance.destroy();
                
                // Remove from array
                editorInstances.splice(index, 1);
                
                // Remove DOM element with animation
                const element = document.getElementById(editorId);
                element.style.animation = 'slideIn 0.3s ease-out reverse';
                setTimeout(() => element.remove(), 300);
                
                updateStats();
                console.log(`Destroyed editor: ${editorId}`);
            }
        }
        
        function destroyAll() {
            const editors = [...editorInstances];
            editors.forEach(editor => {
                destroyEditor(editor.id);
            });
        }
        
        function toggleTheme(editorId) {
            const editor = editorInstances.find(e => e.id === editorId);
            if (editor) {
                editor.theme = editor.theme === 'solar' ? 'cave' : 'solar';
                OT.setTheme(editor.theme);
            }
        }
        
        function exportContent(editorId) {
            const editor = editorInstances.find(e => e.id === editorId);
            if (editor) {
                const content = editor.instance.getValue();
                console.log(`Content from ${editorId}:`, content);
                
                // Copy to clipboard
                navigator.clipboard.writeText(content).then(() => {
                    alert(`Content copied to clipboard! (${content.length} characters)`);
                });
            }
        }
        
        function getAllContent() {
            const allContent = editorInstances.map(editor => {
                return {
                    id: editor.id,
                    content: editor.instance.getValue(),
                    length: editor.instance.getValue().length
                };
            });
            
            console.log('All editor content:', allContent);
            alert(`Retrieved content from ${allContent.length} editors. Check console for details.`);
        }
        
        function syncAllContent() {
            if (editorInstances.length < 2) {
                alert('Need at least 2 editors to sync content');
                return;
            }
            
            const firstContent = editorInstances[0].instance.getValue();
            editorInstances.slice(1).forEach(editor => {
                editor.instance.setValue(firstContent);
            });
            
            updateStats();
            console.log('Synced content across all editors');
        }
        
        function randomizeThemes() {
            const themes = ['solar', 'cave'];
            editorInstances.forEach(editor => {
                const randomTheme = themes[Math.floor(Math.random() * themes.length)];
                editor.theme = randomTheme;
            });
            // Apply the last theme globally (this will affect all editors)
            if (editorInstances.length > 0) {
                OT.setTheme(editorInstances[editorInstances.length - 1].theme);
            }
            
            console.log('Randomized all themes');
        }
        
        function updateStats() {
            document.getElementById('editorCount').textContent = editorInstances.length;
            document.getElementById('totalCreated').textContent = totalCreated;
            
            const totalChars = editorInstances.reduce((sum, editor) => {
                return sum + editor.instance.getValue().length;
            }, 0);
            document.getElementById('totalChars').textContent = totalChars;
        }
        
        // Create initial editor on load
        window.addEventListener('DOMContentLoaded', () => {
            createEditor();
        });
        
        // Cleanup on page unload
        window.addEventListener('beforeunload', () => {
            editorInstances.forEach(editor => {
                editor.instance.destroy();
            });
        });
    </script>
</body>
</html>